<?php defined('SYSPATH') or die('No direct script access.');

class SeminarChoice_Controller extends UserController {

    public function __construct() {
        parent::__construct();
        $this->activeMenuItem = UserMenu::$SEMINAR_CHOICE;
    }

    public function index() {
        
        // LocalSeminars
        // Select all current seminars and join not-cancelled registration if there is any.
        $query = 'SELECT se.*, reg.created_at AS reg_created_at, reg.id AS reg_id ' .
                'FROM vi_seminar se ' .
                'LEFT OUTER JOIN vi_registration reg ON reg.vi_seminar_id = se.id AND reg.person_id = :person_id AND reg.cancelled_at IS NULL ';
        if ($this->getAuthUser('is_admin')) {
            $query .= 'WHERE se.end_date >= :today ';
        }
        else {
            $query .= 'WHERE se.begin_date > :today ';
        }
        $query .= 'AND se.active = :true ORDER BY se.begin_date, se.begin_time';
        $this->viewData['viSeminarList'] = $this->dao->queryAll($query,
                array(
                    'person_id' => $this->getAuthOrSubstituteUser('id'),
                    'today' => date::today(),
                    'true' => sql::$TRUE
        ));
        
        // International seminars
        $this->viewData['seminarList'] = $this->dao->queryAll(
                'SELECT se.*, l10n.name, l10n.description ' .
                'FROM seminar se ' .
                'LEFT OUTER JOIN seminar_l10n l10n ON se.id = l10n.seminar_id AND l10n.language_code = :language_code ' .
                'WHERE se.end_date > :today AND se.active = :active ' .
                'ORDER BY se.begin_date, se.begin_time',
                array(
                    'language_code' => $this->getL10nLanguageCode(),
                    'today' => date::today(),
                    'active' => sql::$TRUE
                )
        );
        foreach ($this->viewData['seminarList'] as &$seminar) {
            $seminar['registrationList']  = $this->dao->queryAll(
                    'SELECT * FROM registration ' .
                    'WHERE seminar_id = :seminar_id AND person_id = :person_id ' .
                    'ORDER BY id',
                    array('seminar_id' => $seminar['id'], 'person_id' => $this->getAuthOrSubstituteUser('id'))
            );
        }
        
        $this->renderSubview('/user/seminarChoice');
    }
}